﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace ToolRental.Client.SMvvm.Admin
{
    public class TextBoxWithWatermark : TextBox
    {
        #region WaterMarkTextProperty Dependency property
        public string Watermark
        {
            get { return (string)GetValue(WaterMarkTextProperty); }
            set { SetValue(WaterMarkTextProperty, value); }
        }
        public static readonly DependencyProperty WaterMarkTextProperty =
            DependencyProperty.Register("WatermarkText", typeof(string), typeof(TextBoxWithWatermark), new PropertyMetadata(new PropertyChangedCallback(OnWatermarkTextChanged)));
        #endregion

        private bool isWatermarkDisplayed = false;
        private Binding textBinding = null;

        public TextBoxWithWatermark()
        {
            Loaded += (s, ea) => ShowWatermarkText();
        }

        #region OnGotFocus
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            HideWatermarkText();
        }
        #endregion

        #region OnLostFocus
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            ShowWatermarkText();
        }
        #endregion

        #region OnWatermarkTextChanged
        private static void OnWatermarkTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var textBox = sender as TextBoxWithWatermark;
            if (textBox == null || !textBox.IsLoaded) return;
            textBox.ShowWatermarkText();
        }
        #endregion

        #region ShowWatermark
        private void ShowWatermarkText()
        {
            if (String.IsNullOrEmpty(Text) && !String.IsNullOrEmpty(Watermark))
            {
                isWatermarkDisplayed = true;
                textBinding = BindingOperations.GetBinding(this, TextProperty);
                BindingOperations.ClearBinding(this, TextProperty);
                Foreground = new SolidColorBrush(Colors.Gray);
                Text = Watermark;
            }
        }
        #endregion

        #region HideWatermarkText
        private void HideWatermarkText()
        {
            if (isWatermarkDisplayed)
            {
                isWatermarkDisplayed = false;
                ClearValue(ForegroundProperty);
                Text = "";
                if (textBinding != null) SetBinding(TextProperty, textBinding);
            }
        }
        #endregion

    }
}
